/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.jca;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyStore.Entry;
import java.security.KeyStore.LoadStoreParameter;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore.ProtectionParameter;
import java.security.KeyStoreException;
import java.security.KeyStoreSpi;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * HSM Proxy Key Store implementation. Usage:
 * 
 * <pre>
 * KeyStore keyStore = KeyStore.getInstance(&quot;HSMProxy&quot;);
 * </pre>
 * 
 * @author Frank Cornelis
 * 
 */
public class HSMProxyKeyStore extends KeyStoreSpi {

	private static final Log LOG = LogFactory.getLog(HSMProxyKeyStore.class);

	/**
	 * KeyStore is not thread-safe, so we can afford to share the JAX-WS client.
	 */
	private HSMProxyKeyStoreParameter keyStoreParameter;

	@Override
	public Key engineGetKey(String alias, char[] password)
			throws NoSuchAlgorithmException, UnrecoverableKeyException {
		return new HSMProxyPrivateKey(alias, this.keyStoreParameter);
	}

	@Override
	public Certificate[] engineGetCertificateChain(String alias) {
		List<X509Certificate> certificateChain;
		try {
			certificateChain = this.keyStoreParameter.getHSMProxyClient()
					.getCertificateChain(alias);
		} catch (CertificateException e) {
			LOG.error("certificate error: " + e.getMessage(), e);
			return null;
		}
		Certificate[] result = new Certificate[certificateChain.size()];
		return certificateChain.toArray(result);
	}

	@Override
	public Certificate engineGetCertificate(String alias) {
		try {
			List<X509Certificate> certificateChain = this.keyStoreParameter
					.getHSMProxyClient().getCertificateChain(alias);
			return certificateChain.get(0);
		} catch (CertificateException e) {
			LOG.error("certificate error: " + e.getMessage(), e);
			return null;
		}
	}

	@Override
	public Date engineGetCreationDate(String alias) {
		return null;
	}

	@Override
	public void engineSetKeyEntry(String alias, Key key, char[] password,
			Certificate[] chain) throws KeyStoreException {
	}

	@Override
	public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain)
			throws KeyStoreException {
	}

	@Override
	public void engineSetCertificateEntry(String alias, Certificate cert)
			throws KeyStoreException {
	}

	@Override
	public void engineDeleteEntry(String alias) throws KeyStoreException {
	}

	@Override
	public Enumeration<String> engineAliases() {
		Set<String> aliases = this.keyStoreParameter.getHSMProxyClient()
				.getAliases();
		Vector<String> aliasesVector = new Vector<String>();
		for (String alias : aliases) {
			aliasesVector.add(alias);
		}
		return aliasesVector.elements();
	}

	@Override
	public boolean engineContainsAlias(String alias) {
		Set<String> aliases = this.keyStoreParameter.getHSMProxyClient()
				.getAliases();
		return aliases.contains(alias);
	}

	@Override
	public int engineSize() {
		Set<String> aliases = this.keyStoreParameter.getHSMProxyClient()
				.getAliases();
		return aliases.size();
	}

	@Override
	public boolean engineIsKeyEntry(String alias) {
		Set<String> aliases = this.keyStoreParameter.getHSMProxyClient()
				.getAliases();
		return aliases.contains(alias);
	}

	@Override
	public boolean engineIsCertificateEntry(String alias) {
		return false;
	}

	@Override
	public String engineGetCertificateAlias(Certificate cert) {
		return null;
	}

	@Override
	public void engineStore(OutputStream stream, char[] password)
			throws IOException, NoSuchAlgorithmException, CertificateException {
	}

	@Override
	public void engineLoad(InputStream stream, char[] password)
			throws IOException, NoSuchAlgorithmException, CertificateException {
	}

	@Override
	public void engineLoad(LoadStoreParameter param) throws IOException,
			NoSuchAlgorithmException, CertificateException {
		if (null == param) {
			throw new NoSuchAlgorithmException("requires a load parameter");
		}
		this.keyStoreParameter = (HSMProxyKeyStoreParameter) param;
	}

	@Override
	public Entry engineGetEntry(String alias, ProtectionParameter protParam)
			throws KeyStoreException, NoSuchAlgorithmException,
			UnrecoverableEntryException {
		PrivateKey privateKey = (PrivateKey) engineGetKey(alias, null);
		Certificate[] certificateChain = engineGetCertificateChain(alias);
		PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey,
				certificateChain);
		return privateKeyEntry;
	}
}
